package com.jsgt.greekfire.ui.trading.currencytrading

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.text.*
import android.view.View
import android.widget.EditText
import android.widget.RadioGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.fhx.core.base.BaseFragment
import com.fhx.core.utils.SoftKeyboardUtils
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.App
import com.jsgt.greekfire.IS_ACTIVATION
import com.jsgt.greekfire.LOGIN_STATUS
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.*
import com.jsgt.greekfire.common.listener.OnItemClickListener
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.common.util.TimeUtil
import com.jsgt.greekfire.common.websocket.Message
import com.jsgt.greekfire.common.websocket.MyWebSocketClient
import com.jsgt.greekfire.common.websocket.MyWebSocketClientManager
import com.jsgt.greekfire.common.widget.maxDecimalPlace
import com.jsgt.greekfire.dao.model.MarketBean
import com.jsgt.greekfire.dialog.SecurityPwdDialog
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.event.GFTPriceEvent
import com.jsgt.greekfire.event.MarketBuyOrSellEvent
import com.jsgt.greekfire.event.TradingEvent
import com.jsgt.greekfire.factory.CoinViewModelFactory
import com.jsgt.greekfire.ui.home.entrance.EntranceActivity
import com.jsgt.greekfire.ui.trading.KLineActivity
import com.jsgt.greekfire.ui.trading.adapter.TickMarketAdapter
import com.jsgt.greekfire.ui.trading.adapter.UserEntrustAdapter
import com.jsgt.greekfire.ui.trading.dialog.TradingCoinSelectPopup
import com.jsgt.greekfire.viewmodel.CoinViewModel
import com.jsgt.greekfire.viewmodel.TradingViewModel
import com.scwang.smartrefresh.header.MaterialHeader
import com.xw.repo.BubbleSeekBar
import com.xw.repo.BubbleSeekBar.OnProgressChangedListenerAdapter
import kotlinx.android.synthetic.main.fragment_currency_trading.*
import kotlinx.android.synthetic.main.layout_text_one.*
import kotlinx.android.synthetic.main.view_trading_header.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.java_websocket.handshake.ServerHandshake
import org.jetbrains.anko.textColor
import java.math.BigDecimal
import java.text.DecimalFormat

/**
 * 币币交易
 */
class CurrencyTradingFragment : BaseFragment(), RadioGroup.OnCheckedChangeListener,
    View.OnClickListener {
    private val coinViewModel: CoinViewModel by lazy {
        ViewModelProvider(
            this,
            CoinViewModelFactory()
        ).get(CoinViewModel::class.java)
    }

    private val tradingViewModel: TradingViewModel by lazy {
        ViewModelProvider(this).get(TradingViewModel::class.java)
    }

    private val mOneAdapter: TickMarketAdapter by lazy { TickMarketAdapter() }// 买入适配器
    private val mTwoAdapter: TickMarketAdapter by lazy { TickMarketAdapter() }// 卖出适配器
    private var lastTime = 0L //交易数据最后刷新时间
    private var lastTime1 = 0L //最新价格最后刷新时间
    private val spacingTime = 300 //刷新间隔时间 - 毫秒
    private val userEntrustAdapter: UserEntrustAdapter by lazy { UserEntrustAdapter() }

    private var canUseUSDT = 0.0
    private var canUseCoin = 0.0
    private var canUse = 0.0

    val df = DecimalFormat("######0.0000")
    val df1 = DecimalFormat("######0.00")

    //    private val tradingInfoFragment by lazy {
//        TradingInfoFragment()
//    }/
    private var pwdDialog: SecurityPwdDialog? = null

    var myWebSocketClient: MyWebSocketClient? = null
    var onSocketList: MyWebSocketClient.OnSocketListener? = null

    var page = 1
    val limit = 100

    var entrustCoinList: MutableList<EntrustCoin>? = null

    private var entrustCoin: EntrustCoin? = null

    override fun getLayoutId(): Int = R.layout.fragment_currency_trading

    override fun main() {
        radioGroupCheck()
        changeImp()

        mOneAdd.setOnClickListener(this)
        mOneSum.setOnClickListener(this)
        btnOneBuy.setOnClickListener(this)
        ll_title_left.setOnClickListener(this)
        imv_title_right.setOnClickListener(this)

        ll_current_trust.setOnClickListener(this)
        ll_history_trust.setOnClickListener(this)

        mOneAdapter.itemClickListner = {
            mOnePrice.setText(it.dealAmount.toString())
        }
        recyclerOne.adapter = mOneAdapter
        val layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, true)
        mOneAdapter.isStackFromEnd = true
        recyclerOne.layoutManager = layoutManager

        mTwoAdapter.itemClickListner = {
            mOnePrice.setText(it.dealAmount.toString())
        }
        recyclerTwo.adapter = mTwoAdapter
        recyclerTwo.layoutManager = LinearLayoutManager(activity)

        userEntrustAdapter.onCancelClickListener = {
            tradingViewModel.cancelUserEntrust(
                mapOf(
                    "coinCode" to it.coinCode,
                    "fixedCode" to it.fixedCode,
                    "guid" to it.guid
                )
            )
        }
        recyclerThree.adapter = userEntrustAdapter
        recyclerThree.layoutManager = LinearLayoutManager(activity)

        tradingViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            refreshView.finishRefresh()
            refreshView.setEnableLoadMore(false)
            ToastUtils.show(it.toString())
        })
        tradingViewModel.entrustCoinListLiveData.observe(this, Observer {
            if (it != null && it.isNotEmpty()) {
                contentView.visibility = View.VISIBLE
                entrustCoinList = it as MutableList<EntrustCoin>?
                txv_title_left.text = it[0].dealKey?.replace("_", "/")
                entrustCoin = it[0]
                refreshData()
                connectSocket()
            }
        })

        /*   entrustCoinList = mutableListOf(
               EntrustCoin("ZWB", "USDT", "ZWB_USDT"),
               EntrustCoin("JJB", "USDT", "JJB_USDT"),
               EntrustCoin("FHB", "USDT", "FHB_USDT"),
               EntrustCoin("LTB", "USDT", "LTB_USDT")
           )*/
        if (entrustCoinList != null) {
            txv_title_left.text = entrustCoinList!![0].dealKey?.replace("_", "/")
            entrustCoin = entrustCoinList!![0]
        } else {
            tradingViewModel.getEntrustCoinList()
        }

        tradingViewModel.tickMarketLiveData.observe(this, Observer {
            if (it != null) {
                val nowTime = TimeUtil.getNow()
                if (nowTime - lastTime > spacingTime) {
                    lastTime = nowTime
                    if (!it.sell.isNullOrEmpty()) {
                        mOneAdapter.refreshData(it.sell!!)
                    } else {
                        mOneAdapter.clearData()
                    }

                    if (!it.buy.isNullOrEmpty()) {
                        mTwoAdapter.refreshData(it.buy!!)
                    } else {
                        mTwoAdapter.clearData()
                    }
                }
            }
        })

        tradingViewModel.newPriceLiveData.observe(this, Observer {
            refreshView.finishRefresh()
            val nowTime = TimeUtil.getNow()
            App.context.gftPrice = it.newPrice
            EventBus.getDefault().post(GFTPriceEvent(it.newPrice))

            if (nowTime - lastTime1 > spacingTime) {
                lastTime1 = nowTime
                mTvPanJia.text = it?.newPrice.toString()
                mTvMoney.text = "CNY ≈ ${df1.format(it?.newPrice?.times(7))}"

                if (mOnePrice.text.isNullOrEmpty()) {
                    mOnePrice.setText(it?.newPrice?.toString())
                    endSelection(mOnePrice)
                }

                try {
                    val per = if (it.lastPrice == 0.0) {
                        0.0
                    } else {
                        (it.newPrice - it.lastPrice) / it.lastPrice * 100
                    }
                    if (per >= 0) {
                        mTvRange.textColor = ContextCompat.getColor(activity!!, R.color.typeGreen)
                        mTvRange.text = "+" + df1.format(per) + "%"
                    } else {
                        mTvRange.textColor = ContextCompat.getColor(activity!!, R.color.typeRed)
                        mTvRange.text = df1.format(per) + "%"
                    }
                } catch (error: Exception) {
                    mTvRange.textColor = ContextCompat.getColor(activity!!, R.color.typeGreen)
                    mTvRange.text = df1.format(0) + "%"
                }
            }
        })
        tradingViewModel.addUserEntrustLiveData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show("成功")
            var dealKey = txv_title_left.text.toString().trim().replace("/", "_")
            recyclerThree.postDelayed({
                tradingViewModel.getUserEntrust(
                    mapOf(
                        "dealStatus" to if (current_trust_underline.visibility == 0) 6 else 7,
                        "dealKey" to dealKey,
                        "page" to page,
                        "limit" to limit
                    )
                )
            }, 500)
            NetDataManager.getUserAssets()
        })

        tradingViewModel.userEntrustLiveData.observe(this, Observer {
            refreshView.finishRefresh()
            refreshView.finishLoadMore()
            if (it != null) {
                if (page == 1 && it.list.size <= 0) {
                    textView_msg.visibility = View.VISIBLE
                } else {
                    textView_msg.visibility = View.GONE
                }
                when {
                    it.totalPage > page -> {
                        refreshView.setEnableLoadMore(true)
                        page++
                        userEntrustAdapter.refreshData(it.list)
                    }
                    (it.totalPage == 0 || it.totalPage == page) -> {
                        refreshView.setEnableLoadMore(false)
                        userEntrustAdapter.refreshData(it.list)
                    }
                    else -> {
                        refreshView.setEnableLoadMore(false)
                    }
                }
            }
        })

        tradingViewModel.cancelUserEntrustLiveData.observe(this, Observer {
            ToastUtils.show(context!!.resources.getString(R.string.revocation_success))
            NetDataManager.getUserAssets()
        })

        if (LOGIN_STATUS && IS_ACTIVATION != 1) {
            var dealKey = txv_title_left.text.toString().trim().replace("/", "_")
            tradingViewModel.getUserEntrust(
                mapOf(
                    "dealStatus" to if (current_trust_underline.visibility == 0) 6 else 7,
                    "dealKey" to dealKey,
                    "page" to page,
                    "limit" to limit
                )
            )
            NetDataManager.getUserAssets()
        }

        val materialHeader = MaterialHeader(context)
        materialHeader.setColorSchemeResources(R.color.black)
        refreshView.setRefreshHeader(materialHeader)
        refreshView.setEnableLoadMore(false)
        refreshView.setOnRefreshListener {
            if (entrustCoinList == null) {
                tradingViewModel.getEntrustCoinList()
                return@setOnRefreshListener
            }
            if (entrustCoin == null || entrustCoin!!.dealKey == null) {
                refreshView.postDelayed(Runnable {
                    refreshView.finishRefresh()
                }, 500)
                return@setOnRefreshListener
            }
            refreshData();
        }
        refreshView.setOnLoadMoreListener {
            if (LOGIN_STATUS && IS_ACTIVATION != 1) {
                page++
                var dealKey = txv_title_left.text.toString().trim().replace("/", "_")
                tradingViewModel.getUserEntrust(
                    mapOf(
                        "dealStatus" to if (current_trust_underline.visibility == 0) 6 else 7,
                        "dealKey" to dealKey,
                        "page" to page,
                        "limit" to limit
                    )
                )
            }
        }
//        contentView.visibility = View.GONE
        refreshView.autoRefresh()
    }

    fun refreshData() {
        tradingViewModel.getTickMarket(entrustCoin!!.dealKey!!)
        tradingViewModel.getNewPrice(entrustCoin!!.dealKey!!)
//        if (LOGIN_STATUS && IS_ACTIVATION != 1) {
        if (LOGIN_STATUS) {
            page = 1
            var dealKey = txv_title_left.text.toString().trim().replace("/", "_")
            tradingViewModel.getUserEntrust(
                mapOf(
                    "dealStatus" to if (current_trust_underline.visibility == 0) 6 else 7,
                    "dealKey" to dealKey,
                    "page" to page,
                    "limit" to limit
                )
            )
            NetDataManager.getUserAssets()
        }
    }

    private fun radioGroupCheck() {
        mRadioGroup!!.setOnCheckedChangeListener(this)
        btnOneBuy!!.setOnClickListener(this)
        mOneSeekBar.setThumbColor(resources.getColor(R.color.trading_buy))
        mOneSeekBar.setSecondTrackColor(resources.getColor(R.color.trading_buy))
        btnOneBuy.setBackgroundResource(R.drawable.bg_trading_btn_buy)
        btnOneBuy.text = getString(R.string.text_buy)
    }

    private fun changeImp() {
        mOneSeekBar.onProgressChangedListener = object : OnProgressChangedListenerAdapter() {
            override fun onProgressChanged(
                bubbleSeekBar: BubbleSeekBar,
                progress: Int,
                progressFloat: Float
            ) {
                if (mTabOne.isChecked) {
                    var price = 0.0
                    if (!mOnePrice.text.isNullOrEmpty() && !mOnePrice.text.toString()
                            .isNullOrEmpty()
                    ) {
                        price = mOnePrice.text?.toString()?.toDouble()!!
                    }
                    if (price == 0.0) {
                        mOneTCP.setText("")
                    } else {  //买入时 （可用USDT * 百分比 / 价格）
                        val num = progressFloat * canUse / 100 / price
                        if (num == 0.0) {
                            mOneTCP.setText("")
                        } else {
                            mOneTCP.setText(df.format(num).replace(".0000", ""))
                        }
                        endSelection(mOneTCP)
                    }
                } else { //卖出时 （可用GFT * 百分比）
                    val num = progressFloat * canUse / 100
                    if (num == 0.0) {
                        mOneTCP.setText("")
                    } else {
                        mOneTCP.setText(df.format(num).replace(".0000", ""))
                    }
                    endSelection(mOneTCP)
                }
                text_one_kaishi.text = df1.format(progressFloat) + "%"
            }

            override fun getProgressOnActionUp(
                bubbleSeekBar: BubbleSeekBar,
                progress: Int,
                progressFloat: Float
            ) {
//                mOneTCP.setText(progress.toString())
            }

            override fun getProgressOnFinally(
                bubbleSeekBar: BubbleSeekBar,
                progress: Int,
                progressFloat: Float
            ) {

            }
        }
        mOnePrice.maxDecimalPlace(4)
        mOnePrice.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s.isNullOrEmpty()) {
                    mTvOneBuy.text = "≈0 CNY"
                } else {
                    var cny = "0"
                    try {
                        cny = df1.format(s.toString().toDouble() * 7).replace(".0000", "")
                    } catch (error: java.lang.Exception) {
                        mOnePrice.setText("")
                    }
                    mTvOneBuy.text = "≈$cny CNY"
                }
            }

            override fun afterTextChanged(s: Editable?) {
                if (s.isNullOrEmpty()) {
                    mTvOneBuy.text = "≈0 CNY"
                } else {
                    try {
                        s.toString().toDouble()
                        refreshTurnover()
                        val cny  = df1.format(s.toString().toDouble() * 7).replace(".0000", "")
                        mTvOneBuy.text = "≈$cny CNY"
                    } catch (error: java.lang.Exception) {
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }
        })

        mOneTCP.maxDecimalPlace(4)
        mOneTCP.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (!s.isNullOrEmpty()) {
                    try {
                        s.toString().toDouble()
                        refreshTurnover()
                    } catch (error: java.lang.Exception) {
                    }
                }

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })
    }

    /**
     * 设置EditText游标至末尾
     */
    private fun endSelection(editText: EditText) {
        val text: CharSequence = editText.text
        if (text is Spannable) {
            val spanText: Spannable = text as Spannable
            Selection.setSelection(spanText, text.length)
        }
    }

    /**
     * 刷新交易额 价格*数量
     */
    private fun refreshTurnover() {
        val price = mOnePrice.text
        val num = mOneTCP.text
        if (!TextUtils.isEmpty(price) && !TextUtils.isEmpty(num)) {
            val sss = df.format(price.toString().toDouble() * num.toString().toDouble())
                .replace(".0000", ".0")
            mOneDeal.text = sss
        } else {
            mOneDeal.text = "0.0"
        }
    }

    private fun initDialog() {
        pwdDialog = SecurityPwdDialog(context!!, R.style.dialog)
        pwdDialog?.inputCallback = object : SecurityPwdDialog.InputCallback {
            override fun callBack(result: String) {
                if (buy_rb.isChecked) {
                    submit("1", result)
                } else {
                    submit("0", result)
                }
            }
        }
    }

    /**
     * adType:1.买 0.卖
     */
    private fun submit(adType: String, password: String) {
        val price = price_uti_view.getText()
        val num = num_coin_view.getText()
        coinViewModel.sellCoin(num, "3", price, password, adType)
    }

    /**
     * 买入，卖出
     */
    private fun buy() {
        if (LOGIN_STATUS) {
            if (IS_ACTIVATION == 1) {
                ToastUtils.show(context!!, getString(R.string.account_no_activation))
            } else {
                if (entrustCoin != null && entrustCoin!!.coinCode != null) {
                    val price = mOnePrice.text
                    val num = mOneTCP.text
                    if (TextUtils.isEmpty(price) || price.toString().toDouble() == 0.0) {
                        ToastUtils.show(context!!, "请输入价格")
                        return
                    }
                    if (TextUtils.isEmpty(num) || num.toString().toDouble() == 0.0) {
                        ToastUtils.show(context!!, "请输入数量")
                        return
                    }
                    mOnePrice?.clearFocus()
                    mOneTCP?.clearFocus()

//                initDialog()
//                pwdDialog?.nameTv?.text = "USDT"
//                pwdDialog?.numberTv?.text = price_uti_view.getText()
//                pwdDialog?.show()

                    var map = HashMap<String, Any>()
                    if (mTabOne.isChecked) { //买
                        map["dealType"] = 1
                    } else { // 卖
                        map["dealType"] = 2
                    }
                    map["dealAmount"] = price.toString().toDouble()
                    map["dealNum"] = num.toString().toDouble()
                    map["coinCode"] = entrustCoin!!.coinCode!!
                    map["fixedCode"] = entrustCoin!!.fixedCode!!
                    map["dealWay"] = 1
                    showProgress(true)

                    tradingViewModel.addUserEntrust(map)
                }
            }
        } else {
            EntranceActivity.start(context!!)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFollowEvent(e: TradingEvent) {
        if (LOGIN_STATUS) {
            coinViewModel.saleCoinList()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
//        NetDataManager.getUserAssets()

        for (assetsBean in NetDataManager.assetsList) {
            if (assetsBean.assetName.equals(entrustCoin!!.coinCode)) {
                if (!mTabOne.isChecked) {
                    //mOneYuE.text = entrustCoin!!.coinCode + PriceFormatUtil.format(assetsBean.assetBalance, 4)
                    mOneYuE.text =  "${entrustCoin!!.coinCode}${BigDecimal(assetsBean.assetBalance.toString()).setScale(4,BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString()}"
                    canUse = assetsBean.assetBalance!!
                }
            }
            if (assetsBean.assetName.equals("USDT")) {
                if (mTabOne.isChecked) {
                    //mOneYuE.text = "USDT ${PriceFormatUtil.format(assetsBean.assetBalance, 4)}"
                    mOneYuE.text =  "USDT ${BigDecimal(assetsBean.assetBalance.toString()).setScale(4,BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString()}"
                    canUse = assetsBean.assetBalance!!
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMarketBuyOrSellEvent(e: MarketBuyOrSellEvent) {
        when (e.type) {
            1 -> {
                mRadioGroup.check(R.id.mTabOne)
                mOnePrice.setText(e.tickMarketItem?.dealAmount.toString())
                endSelection(mOnePrice)
            }
            2 -> {
                mRadioGroup.check(R.id.mTabTwo)
                mOnePrice.setText(e.tickMarketItem?.dealAmount.toString())
                endSelection(mOnePrice)
            }
        }
    }

    override fun onDestroyView() {
        MyWebSocketClientManager.instance.destroyClient(onSocketList)
        myWebSocketClient = null
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
        pwdDialog = null
    }

    @SuppressLint("SetTextI18n")
    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when (checkedId) {
            R.id.mTabOne -> {
//            mOneSeekBar.setTrackColor(resources.getColor(R.color.typeGreen))
                mOneSeekBar.setThumbColor(resources.getColor(R.color.trading_buy))
                mOneSeekBar.setSecondTrackColor(resources.getColor(R.color.trading_buy))
                btnOneBuy.setBackgroundResource(R.drawable.bg_trading_btn_buy)
//                mOneYuE.text = "${entrustCoin?.fixedCode} ${PriceFormatUtil.format(canUseUSDT, 4)}"
                mOneTextType.text = entrustCoin?.fixedCode
//                canUse = canUseUSDT
                mOneSeekBar.setProgress(0.0f)
                btnOneBuy.text = context!!.resources.getString(R.string.text_buy)
//            mOneSeekBar.setBubbleColor(resources.getColor(R.color.typeGreen))
                NetDataManager.getUserAssets()
            }

            R.id.mTabTwo -> {
//                mOneSeekBar.setTrackColor(resources.getColor(R.color.typeRed))
                btnOneBuy.setBackgroundResource(R.drawable.bg_trading_btn_sell)
                mOneSeekBar.setThumbColor(resources.getColor(R.color.trading_sell))
                mOneSeekBar.setSecondTrackColor(resources.getColor(R.color.trading_sell))
//                mOneYuE.text = "${entrustCoin?.coinCode} ${PriceFormatUtil.format(canUseCoin, 4)}"
                mOneTextType.text = entrustCoin?.coinCode
//                canUse = canUseCoin
                mOneSeekBar.setProgress(0.0f)
                btnOneBuy.text = context!!.resources.getString(R.string.text_sale)
//                mOneSeekBar.setBubbleColor(resources.getColor(R.color.typeRed))
                NetDataManager.getUserAssets()
            }
        }
    }

    override fun onClick(v: View?) {
        SoftKeyboardUtils.hide(activity)
        when (v?.id) {
            R.id.ll_current_trust -> {
                refreshView.autoRefresh()
                tv_current_trust.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tv_history_trust.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                current_trust_underline.visibility = View.VISIBLE
                history_trust_underline.visibility = View.GONE
            }
            R.id.ll_history_trust -> {
                refreshView.autoRefresh()
                tv_current_trust.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                tv_history_trust.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                current_trust_underline.visibility = View.GONE
                history_trust_underline.visibility = View.VISIBLE
            }
            R.id.mOneAdd -> {
                try {
                    var num = 0.0
                    if (mOnePrice.text.isNotEmpty()) {
                        num = mOnePrice.text.toString().toDouble()
                    }
                    mOnePrice.setText(
                        DecimalFormat("#0.0000").format(num.plus(0.1))
                    )
                    endSelection(mOnePrice)
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
            }
            R.id.mOneSum -> {
                try {
                    var num: Double = 0.0
                    if (mOnePrice.text.isNotEmpty()) {
                        num = mOnePrice.text.toString().toDouble()
                    }
                    if (num.minus(0.1) >= 0) {
                        mOnePrice.setText(
                            DecimalFormat("#0.0000").format(num.minus(0.1))
                        )
                    } else {
                        mOnePrice.setText(
                            DecimalFormat("#0.0000").format(0.0)
                        )
                    }
                    endSelection(mOnePrice)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            R.id.btnOneBuy -> {
                buy()
            }
            R.id.imv_title_right -> {
                if (entrustCoin != null && !TextUtils.isEmpty(entrustCoin!!.dealKey)) {
                    val marketBean = MarketBean()
                    marketBean.symbol = entrustCoin!!.dealKey!!
                    marketBean.last = 0.0
                    marketBean.changePercentage = "+0.00%"
                    context?.let { KLineActivity.start(it, marketBean) }
                }
            }
            R.id.ll_title_left -> {
                if (entrustCoinList != null) {
                    showCoinSelectDialog(v)
                } else {
                    tradingViewModel.getEntrustCoinList()
                }
            }
        }
    }

    var coinSelectPopup: TradingCoinSelectPopup<EntrustCoin>? = null
    private fun showCoinSelectDialog(v: View) {
        if (coinSelectPopup == null) {
            coinSelectPopup = TradingCoinSelectPopup(context)
            coinSelectPopup?.refresh(entrustCoinList!!)
            coinSelectPopup?.onItemClickListener =
                object : OnItemClickListener<EntrustCoin> {
                    override fun onItemClick(t: EntrustCoin) {
                        txv_title_left.text = t.dealKey?.replace("_", "/")
                        entrustCoin = t
                        refreshView.autoRefresh()
                        mTabOne.performClick()
                        connectSocket();
                    }
                }
        }
        if (!coinSelectPopup!!.isShowing) {
            coinSelectPopup?.showAsDropDown(v)
        }
    }

    private fun connectSocket() {
        val client = MyWebSocketClientManager.instance.createClient(entrustCoin?.dealKey!!)
        if (client == myWebSocketClient) {
            return
        }
        //连接socket
        myWebSocketClient = client
        onSocketList = object : MyWebSocketClient.OnSocketListener {
            override fun onOpen(handshakedata: ServerHandshake?) {
            }

            override fun onMessage(
                message1: Message<GFTKLineData?>?,
                message2: Message<NewPrice?>?,
                message3: Message<TickMarket?>?
            ) {
                if (message2 != null) {
                    tradingViewModel.newPriceLiveData.postValue(message2.data)
                }

                if (message3 != null) {
                    tradingViewModel.tickMarketLiveData.postValue(message3.data)
                }
            }

            override fun onClose(code: Int, reason: String?, remote: Boolean) {
                myWebSocketClient!!.reconnect()
            }

            override fun onError(ex: java.lang.Exception?) {
            }

        }
        myWebSocketClient!!.addOnSocketListener(onSocketList)
        myWebSocketClient!!.connect()
    }
}
